<template>
  <div class="company-links-page">
    <div class="page-header">
      <h1>合作链接管理</h1>
    </div>
    <div class="content-card">
      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          @click="showAddDialog"
        >
          新增合作链接
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="linkList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="index" label="序号" width="80">
          <template slot-scope="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="链接名称" width="150"></el-table-column>
        <el-table-column prop="url" label="链接URL" min-width="200">
          <template slot-scope="scope">
            <el-link :href="scope.row.url" target="_blank" type="primary">
              {{ scope.row.url }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="链接图片" width="120">
          <template slot-scope="scope">
            <div v-if="scope.row.image" class="link-image">
              <img :src="getImageUrl(scope.row.image)" :alt="scope.row.name" @error="handleImageError" />
            </div>
            <span v-else class="no-image">暂无图片</span>
          </template>
        </el-table-column>
                 <el-table-column prop="remarks" label="备注" min-width="200"></el-table-column>
         <el-table-column label="操作" width="100">
           <template slot-scope="scope">
             <el-button 
               type="danger" 
               size="mini" 
               @click="handleDelete(scope.row)"
             >
               删除
             </el-button>
           </template>
         </el-table-column>
       </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 新增链接对话框 -->
    <el-dialog
      title="新增合作链接"
      :visible.sync="addDialogVisible"
      width="500px"
      @close="resetAddForm"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="链接名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入链接名称"></el-input>
        </el-form-item>
        <el-form-item label="链接URL" prop="url">
          <el-input v-model="addForm.url" placeholder="请输入链接URL"></el-input>
        </el-form-item>
        <el-form-item label="链接图片" prop="image">
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="uploadImage"
          >
            <img v-if="addForm.image" :src="getImageUrl(addForm.image)" class="uploaded-image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">点击上传图片，支持 JPG、PNG 格式</div>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input 
            v-model="addForm.remarks" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddLink" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'CompanyLinks',
  data() {
    return {
      // 表格数据
      linkList: [],
      loading: false,
      
      // 分页
      currentPage: 1,
      pageSize: 5,
      total: 0,
      
      // 新增对话框
      addDialogVisible: false,
      addLoading: false,
      addForm: {
        name: '',
        url: '',
        image: '',
        remarks: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入链接名称', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入链接URL', trigger: 'blur' }
        ]
      }
    }
  },
  
  mounted() {
    this.fetchLinkList()
  },
  
  methods: {
    // 获取链接列表
    async fetchLinkList() {
      this.loading = true
      try {
        const response = await axios.get('/api/pageList', {
            pageNum: this.currentPage,
            pageSize: this.pageSize
        })
        
        if (response.data.code === 200) {
          this.linkList = response.data.data.list
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取链接列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchLinkList()
    },
    
    // 处理每页显示数量变化
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchLinkList()
    },
    
    // 获取图片完整URL
    getImageUrl(imageName) {
      if (!imageName) return ''
      return `http://localhost:8083/image/${imageName}`
    },
    
    // 处理图片加载错误
    handleImageError(event) {
      event.target.style.display = 'none'
      event.target.nextElementSibling && (event.target.nextElementSibling.style.display = 'inline')
    },
    
    // 显示新增对话框
    showAddDialog() {
      this.addDialogVisible = true
    },
    
    // 重置新增表单
    resetAddForm() {
      this.addForm = {
        name: '',
        url: '',
        image: '',
        remarks: ''
      }
      this.$nextTick(() => {
        this.$refs.addForm && this.$refs.addForm.clearValidate()
      })
    },
    
    // 图片上传前的验证
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    
    // 上传图片   注意：后端上传图片和之前写的Get请求和Post请求都不太一样
    async uploadImage(options) {
      try {
        const formData = new FormData()
        formData.append('flimage', options.file)
        
        const response = await axios.post('/api/uploadImage', formData
        // {
        //   headers: {
        //     'Content-Type': 'multipart/form-data'
        //   }
        // })
      )
        
        if (response.data.code === 200) {
          this.$message.success('图片上传成功')
          // 后端返回的是图片文件名
          this.addForm.image = response.data.data     //注意，返回的图片名称
        } else {
          this.$message.error(response.data.msg || '图片上传失败')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$message.error('图片上传失败')
      }
    },
    
    // 新增链接
    async handleAddLink() {
      try {
        await this.$refs.addForm.validate()
        
        this.addLoading = true
        
        // 构建请求数据
        const requestData = {
          id: 0,
          name: this.addForm.name,
          url: this.addForm.url,
          image: this.addForm.image,
          remarks: this.addForm.remarks
        }
        
        const response = await axios.post('/api/addLink', requestData)
        
        if (response.data.code === 200) {
          this.$message.success('添加成功')
          this.addDialogVisible = false
          // 刷新列表数据
          this.fetchLinkList()
        } else {
          this.$message.error(response.data.msg || '添加失败')
        }
      } catch (error) {
        console.error('新增链接失败:', error)
        this.$message.error('新增失败')
      } finally {
                 this.addLoading = false
       }
     },
     
     // 删除链接
     async handleDelete(link) {
        try {
          await this.$confirm(`确定要删除链接"${link.name}"吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });

          const params = new URLSearchParams();
          params.append('id', link.id);

          const response = await axios.post('/api/deleteLink', params
          // , {
          //   headers: {
          //     'Content-Type': 'application/x-www-form-urlencoded'
          //   }
          // }
        );

          if (response.data.code === 200) {
            this.$message.success('删除成功');
            this.fetchLinkList();
          } else {
            this.$message.error(response.data.msg || '删除失败');
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除失败:', error);
            this.$message.error('删除失败');
          }
        }
      }
   }
 }
</script>

<style scoped>
.company-links-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.content-card {
  background: white;
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.link-image {
  width: 80px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.link-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.no-image {
  color: #999;
  font-size: 12px;
}

.action-buttons {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}
</style>
